package me.zhengjie.modules.serviceprovider.service.impl;

import me.zhengjie.modules.serviceprovider.domain.TServiceproviderContract;
import me.zhengjie.modules.serviceprovider.domain.TServiceproviderInfo;
import me.zhengjie.modules.serviceprovider.repository.TServiceproviderInfoRepository;
import me.zhengjie.modules.serviceprovider.service.TServiceproviderInfoService;
import me.zhengjie.modules.serviceprovider.service.dto.TServiceproviderInfoDTO;
import me.zhengjie.modules.system.common.EnumWorkorderStatus;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.service.DictDetailService;
import me.zhengjie.modules.system.service.dto.DictDetailDTO;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.serviceprovider.repository.TServiceproviderContractRepository;
import me.zhengjie.modules.serviceprovider.service.TServiceproviderContractService;
import me.zhengjie.modules.serviceprovider.service.dto.TServiceproviderContractDTO;
import me.zhengjie.modules.serviceprovider.service.dto.TServiceproviderContractQueryCriteria;
import me.zhengjie.modules.serviceprovider.service.mapper.TServiceproviderContractMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Date;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
* @author xuyukun
* @date 2019-07-20
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TServiceproviderContractServiceImpl implements TServiceproviderContractService {
    @Autowired
    private TServiceproviderInfoRepository tServiceproviderInfoRepository;
    @Autowired
    private DictDetailRepository dictDetailRepository;
    @Autowired
    private DictDetailService dictDetailService;
    @Autowired
    private TServiceproviderInfoService tServiceproviderInfoService;
    @Autowired
    private TServiceproviderContractRepository tServiceproviderContractRepository;

    @Autowired
    private TServiceproviderContractMapper tServiceproviderContractMapper;

    @Override
    public Object queryAll(TServiceproviderContractQueryCriteria criteria, Pageable pageable){
        Page<TServiceproviderContract> page = tServiceproviderContractRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(tServiceproviderContractMapper::toDto));
    }

    @Override
    public Object queryAll(TServiceproviderContractQueryCriteria criteria){
        return tServiceproviderContractMapper.toDto(tServiceproviderContractRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public TServiceproviderContractDTO findById(Long id) {
        Optional<TServiceproviderContract> tServiceproviderContract = tServiceproviderContractRepository.findById(id);
        ValidationUtil.isNull(tServiceproviderContract,"TServiceproviderContract","id",id);
        return tServiceproviderContractMapper.toDto(tServiceproviderContract.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TServiceproviderContractDTO create(TServiceproviderContract resources) {
        Timestamp date = new Timestamp(System.currentTimeMillis());
        // resources.setCreatTime(date); 签订时间
        DictDetail dictDetailDTO= dictDetailRepository.findById(resources.getContractItemId()).get();
        if(dictDetailDTO!=null){
            resources.setContractItemName(dictDetailDTO.getLabel());
        }
        TServiceproviderInfo tServiceproviderInfoDTO=tServiceproviderInfoRepository.findById(resources.getServiceproviderId()).get();
        if(tServiceproviderInfoDTO!=null){
            resources.setServiceproviderName(tServiceproviderInfoDTO.getSeproName());
        }
        return tServiceproviderContractMapper.toDto(tServiceproviderContractRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(TServiceproviderContract resources) {
        Optional<TServiceproviderContract> optionalTServiceproviderContract = tServiceproviderContractRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalTServiceproviderContract,"TServiceproviderContract","id",resources.getId());

        TServiceproviderContract tServiceproviderContract = optionalTServiceproviderContract.get();
        // 此处需自己修改
        resources.setId(tServiceproviderContract.getId());
        Timestamp date = new Timestamp(System.currentTimeMillis());
        //resources.setCreatTime(date);  签订时间
        DictDetail dictDetailDTO= dictDetailRepository.findById(resources.getContractItemId()).get();
        if(dictDetailDTO!=null){
            resources.setContractItemName(dictDetailDTO.getLabel());
        }
        TServiceproviderInfo tServiceproviderInfoDTO=tServiceproviderInfoRepository.findById(resources.getServiceproviderId()).get();
        if(tServiceproviderInfoDTO!=null){
            resources.setServiceproviderName(tServiceproviderInfoDTO.getSeproName());
        }
        tServiceproviderContractRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        tServiceproviderContractRepository.deleteById(id);
    }


    private Specification getPredicate(Long contractItemId, Long serviceproviderId, String effectTime) {
        Specification specification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery query, CriteriaBuilder cb) {
                //增加筛选条件
                Predicate predicate = QueryHelp.getPredicate(root, query, cb);

                predicate.getExpressions().add(cb.greaterThanOrEqualTo(root.get("endTime").as(String.class), effectTime));

                predicate.getExpressions().add(cb.lessThanOrEqualTo(root.get("startTime").as(String.class),  effectTime));

                predicate.getExpressions().add(cb.equal(root.get("contractItemId").as(Long.class), contractItemId));

                predicate.getExpressions().add(cb.equal(root.get("serviceproviderId").as(Long.class), serviceproviderId));

                return predicate;
            }
        };
        return specification;
    }

    @Override
    public Optional<TServiceproviderContract> findLastEffectContract(Long contractItemId, Long serviceproviderId, String effectTime) {
        Specification specification = getPredicate(contractItemId, serviceproviderId, effectTime);
        return tServiceproviderContractRepository.findOne(specification) ;
    }
}